import 'package:bxultimate/config/app_config.dart';
import 'package:bxultimate/data/store/auth_store.dart';
import 'package:bxultimate/data/store/config_store.dart';
import 'package:bxultimate/shared/shared.dart';
import 'package:bxultimate/shared/util/util_location.dart';
import 'package:bxultimate/shared/util/util_mqtt.dart';
import 'package:bxultimate/shared/util/util_sp.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class AppInitializer {
  // APP 初始化
  static init() async {
    // 初始化 Flutter 框架
    WidgetsFlutterBinding.ensureInitialized();

    /// 隐藏状态栏。为启动页、引导页设置。完成后修改回显示状态栏。
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    // TODO(weilu): 启动体验不佳。状态栏、导航栏在冷启动开始的一瞬间为黑色，且无法通过隐藏、修改颜色等方式进行处理。。。
    // 相关问题跟踪：https://github.com/flutter/flutter/issues/73351

    // 初始化 SharedPreferences Util.
    await UtilSp.getInstance();

    // 安卓 flutter 沉浸式透明状态栏 #安卓状态栏设置成透明
    if (GetPlatform.isAndroid) {
      SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.light);
      SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
    }

    // 初始化服务地址配置
    String? serverUrl = await UtilSp.getString(AppConstant.SERVER_URL);
    if (serverUrl == '') {
      UtilSp.putString(AppConstant.SERVER_URL, AppConfig.API_URL);
    }


    // String? latlon = await UtilSp.getString(AppConstant.DEVICE_POSITION);
    // if (latlon == '') {
    //   UtilSp.putString(
    //       AppConstant.DEVICE_POSITION, "112.57308627600703,37.877693188442784");
    // }

    initStore();

    connectMqtt();



    // 设置 easyRefresh
    EasyRefresh.defaultFooterBuilder = () => TaurusFooter();
  }

  // 初始化基本缓存
  static void initStore() {
    Get.put<AuthStore>(AuthStore());
    Get.put<ConfigStore>(ConfigStore());
  }

  static void connectMqtt() async {
    await AuthStore.to.getProfile();

    // 检测是否有token
    if (AuthStore.to.isLogin) {
      //  建立连接
      UtilMqtt().connect();

      UtilLocation.getLocation();
    }
  }
}
